package com.ph.myblog.services;
 
import java.util.Iterator;
import java.util.List;
 
import org.hibernate.Query;
import org.hibernate.Session;

import com.ph.myblog.dao.HibernateUtil;
import com.ph.myblog.entity.Article;
import com.ph.myblog.entity.Articletype;

public class ArticleServices {
	
	private Session session;
	
	public ArticleServices() { 
//		new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
		session = HibernateUtil.getSessionFactory().getCurrentSession();
	}
	
	public void add(Article article) throws Exception {
		
		try{ 
			session.beginTransaction(); 
			session.save(article);
			session.getTransaction().commit();
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}
	}

	public int update(Article article) throws Exception {
		 
        session.beginTransaction();
        Query q = session.createQuery("update Article set title = ? ,description=? where id = ? ");
        q.setParameter(0, article.getTitle());
        q.setParameter(1, article.getDescription());
        q.setParameter(2, article.getId());
        int size = q.executeUpdate();
        session.getTransaction().commit();
        return size;
	}
	
	public int delete(Article article) throws Exception {
		try{
			int size = this.delete(article.getId());
	        return size;
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}
	}

	public int delete(int id) throws Exception {
 
        session.beginTransaction();
        Query q = session.createQuery("delete from Article where id = ? ");
        q.setParameter(0, id);
        int size = q.executeUpdate();
        session.getTransaction().commit();
        return size;
	}

	public List<Article> list() throws Exception{ 

		try{
	        session.beginTransaction();
	        List<Article> list= session.createQuery("from Article a order by a.id DESC ").list();
	        session.getTransaction().commit();
	         
	        return list;
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}  
	}
 
	public Article loadBlogById(Article blog) throws Exception {

        session.beginTransaction();
        Query q = session.createQuery("from Article a where a.id = ? ");
        q.setParameter(0, blog.getId());
        List<Article> list = q.list();
        session.getTransaction().commit();
		return list.get(0);
	}
}
